﻿
package com.android.finaltracer.ui;

import java.util.ArrayList;

import android.app.TabActivity;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.RadioButton;
import android.widget.TabHost;

import com.android.finaltracer.FTMapActivity;
import com.android.finaltracer.GetNumberActivity;
import com.android.finaltracer.R;
import com.android.finaltracer.model.FTDataProvider.RelationColumns;
import com.android.finaltracer.model.FTProviderInterface;
import com.android.finaltracer.util.FTKey;
import com.android.finaltracer.util.FinalTracerIntents;

public class FuncShowTabMainActivity extends TabActivity implements
        OnCheckedChangeListener {
    private String TAG = "FuncShowMain";
    private boolean DBG = true;
    private TabHost mHost;
    private Intent intent_model_location;
    private Intent intent_model_settings;

    private final int MESSAGE_UPDATE_POSITION = 1;
    public static final int ONE_ID = Menu.FIRST + 1;
    private int mSelector = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.func_show_tab_main);

        mHost = getTabHost();
        Bundle bundle = this.getIntent().getExtras();
        if (bundle != null) {
            mSelector = bundle.getInt(FTKey.KEY_TAB_SELECET);
        }

        // reflashList();
        // mLocationListView.setAdapter(mLocationAdapter);

        RadioButton button_location = (RadioButton) findViewById(R.id.btn_location);
        RadioButton button_settings = (RadioButton) findViewById(R.id.btn_setting);
        button_location.setOnCheckedChangeListener(this);
        button_settings.setOnCheckedChangeListener(this);

        IntentFilter filter = new IntentFilter();
        filter.addAction(FinalTracerIntents.ACTION_UPDATE_POSITION);
        this.registerReceiver(mBroadcastReciver, filter);

        intent_model_location = new Intent(this, FTMapActivity.class);
        intent_model_settings = new Intent(this, GetNumberActivity.class);

        mHost.addTab(mHost.newTabSpec("laction")
                .setIndicator(getString(R.string.tab_location, null), null)
                .setContent(intent_model_location));
        mHost.addTab(mHost.newTabSpec("setting")
                .setIndicator(getString(R.string.tab_settings, null), null)
                .setContent(intent_model_settings));

        ArrayList<String> phones = getAllBindNumbers();
        if (phones != null && phones.size() > 0) {
            mHost.setCurrentTabByTag("laction");
            button_location.setChecked(true);
        } else {
            // mHost.setCurrentTab(mSelector);
            mHost.setCurrentTabByTag("setting");
            button_settings.setChecked(true);
        }

    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        // TODO Auto-generated method stub
        if (isChecked) {
            switch (buttonView.getId()) {
                case R.id.btn_location:
                    this.mHost.setCurrentTabByTag("laction");
                    // listLayout.setVisibility(View.VISIBLE);
                    // reflashList();
                    break;
                case R.id.btn_setting:
                    this.mHost.setCurrentTabByTag("setting");
                    // listLayout.setVisibility(View.INVISIBLE);
                    // stopAllGps();
                    break;
            }
        }
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MESSAGE_UPDATE_POSITION:
                if (DBG)
                    Log.d(TAG, "ON MESSAGE_UPDATE_POSITION");
                Intent intent = (Intent) msg.obj;
                if (intent == null)
                    Log.d(TAG, "ON MESSAGE_UPDATE_POSITION intent == null");
                if (intent != null) {
                    String number = intent
                            .getStringExtra(FinalTracerIntents.UPDATE_POSITION_PHONENUM);
                    int Lat = intent.getIntExtra(
                            FinalTracerIntents.UPDATE_POSITION_LATITUDE, 0);
                    int Lon = intent.getIntExtra(
                            FinalTracerIntents.UPDATE_POSITION_LONGITUDE, 0);
                    if (number == null || number.isEmpty())
                        break;
                    ContentValues values = new ContentValues();
                    values.put(RelationColumns.NUMBER, number);
                    values.put(RelationColumns.GPS_LAT, Lat);
                    values.put(RelationColumns.GPS_LNG, Lon);
                    FTProviderInterface.getInstance(
                            FuncShowTabMainActivity.this).saveRelationNumber(
                            values);
                }
                break;
        }
    }
    };

    BroadcastReceiver mBroadcastReciver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            String action = intent.getAction();
            if (action.equals(FinalTracerIntents.ACTION_UPDATE_POSITION)) {
                // Bundle bundle = new Bundle();
                // bundle.putString(RelationColumns.NUMBER,
                // intent.getStringExtra(FinalTracerIntents.UPDATE_POSITION_PHONENUM));
                // bundle.putInt(RelationColumns.GPS_LAT,
                // intent.getIntExtra(FinalTracerIntents.UPDATE_POSITION_LATITUDE,
                // 0));
                // bundle.putInt(RelationColumns.GPS_LNG,
                // intent.getIntExtra(FinalTracerIntents.UPDATE_POSITION_LONGITUDE,
                // 0));
                // Message msg = Message.obtain(mHandler,
                // MESSAGE_UPDATE_POSITION);
                // msg.setData(bundle);
                // mHandler.sendMessage(msg);
                Message msg = mHandler.obtainMessage(MESSAGE_UPDATE_POSITION,
                        intent);
                mHandler.sendMessage(msg);
            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        // reflashList();
        // bind service
    }

    @Override
    protected void onPause() {
        super.onPause();
        // stopAllGps();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        this.unregisterReceiver(mBroadcastReciver);
    }

    private ArrayList<String> getAllBindNumbers() {
        ArrayList<String> phoneNums = null;
        Uri phoneUri = Uri
                .parse("content://com.android.ft.provider.data/relations");
        String selection = RelationColumns.WEIGHT_TYPE + "='"
                + RelationColumns.WEIGHT_TYPE_BINDED + "'";
        Cursor mCursor = getContentResolver().query(phoneUri, null, selection,
                null, null);
        if (mCursor != null && mCursor.moveToFirst()) {
            phoneNums = new ArrayList<String>();
            do {
                phoneNums.add(mCursor.getString(mCursor
                        .getColumnIndex(RelationColumns.NUMBER)));
            } while (mCursor.moveToNext());
        }
        return phoneNums;
    }

    // 创建OptionsMenu
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        this.populateMenu(menu);
        return super.onCreateOptionsMenu(menu);
    }

    private void populateMenu(Menu menu) {
        menu.add(Menu.NONE, ONE_ID, Menu.NONE, "帮助");
    }

    // @Override
    // public boolean onMenuItemSelected(int featureId, MenuItem item) {
    // //得到点击的菜单项的ID（此Id是自己设定的）
    // int itemId = item.getItemId();
    //
    // if(ONE_ID == itemId)
    // {
    // Toast.makeText(this, "help", Toast.LENGTH_SHORT).show();
    // }
    // return super.onMenuItemSelected(featureId, item);
    // }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // TODO Auto-generated method stub
        switch (item.getItemId()) {
            case ONE_ID:
                Intent intent = new Intent();
                intent.setClass(FuncShowTabMainActivity.this, HelpActivity.class);
                startActivity(intent);
                break;
        }
        return super.onOptionsItemSelected(item);
    }
}
